@tool
extends EditorProperty

const ATTRIBUTE_DICTIONARY_ITEM_COMP = preload("res://addons/gameplay-ability-system/Scripts/Inspector/components/attibute_comp/AttributeDictionaryItemComp.tscn")

var scrollbar:= VBoxContainer.new()

func _ready() -> void:
	add_child(scrollbar)
	var attribute_dictionary = get_edited_object() as AttributeDictionary
	if attribute_dictionary:
		draw_attributes(attribute_dictionary.attirbute_list)


# 重新绘制所有 attribute item 以及按钮
func draw_attributes(attribute_list:Array[AttributeDictionaryItem]):
	for child in scrollbar.get_children():
		child.queue_free()
		
	for attribute in attribute_list:
		var attribute_dictionary_item = ATTRIBUTE_DICTIONARY_ITEM_COMP.instantiate()
		attribute_dictionary_item.attribute_item = attribute
		attribute_dictionary_item.remove_attribute.connect(_on_remove_attribute)
		scrollbar.add_child(attribute_dictionary_item)
	
	var new_attribute_btn = Button.new()
	new_attribute_btn.pressed.connect(_on_add_attribute_pressed)
	new_attribute_btn.text = "添加 Attribute"
	scrollbar.add_child(new_attribute_btn)


# 当 “添加 [AttributeDictionaryItem]” 按钮被点击
func _on_add_attribute_pressed():
	var attribtue_dictionary = get_edited_object() as AttributeDictionary
	attribtue_dictionary.attirbute_list.append(AttributeDictionaryItem.new())
	save_attribute_set()
	draw_attributes(attribtue_dictionary.attirbute_list)

# 当移除按钮被点击
func _on_remove_attribute(attribute_item:AttributeDictionaryItem):
	var attribute_dictionary = get_edited_object() as AttributeDictionary
	attribute_dictionary.attirbute_list.erase(attribute_item)
	save_attribute_set()
	draw_attributes(attribute_dictionary.attirbute_list)

# 资源保存
func save_attribute_set():
	emit_changed(get_edited_property(), get_edited_object().attirbute_list)
	get_edited_object().notify_property_list_changed()
